package com.yanyu.space.sys.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanyu.space.common.core.bean.db.PageEntity;
import com.yanyu.space.common.db.pagination.PageUtil;
import com.yanyu.space.common.core.exception.DataNotFoundException;
import com.yanyu.space.sys.bean.po.Dic;
import com.yanyu.space.sys.bean.po.DicItem;
import com.yanyu.space.sys.bean.vo.dic.DicSearchVo;
import com.yanyu.space.sys.dao.DicItemMapper;
import com.yanyu.space.sys.dao.DicMapper;
import com.yanyu.space.sys.service.IDicService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据字典 业务实现类
 *
 * @author yanyu
 */
@Service
@Slf4j
@AllArgsConstructor
public class DicServiceImpl extends ServiceImpl<DicMapper, Dic> implements IDicService {

    private DicItemMapper dicItemMapper;

    @Override
    public PageEntity<Dic> listPage(DicSearchVo vo) {
        IPage<Dic> page = baseMapper.listPage(PageUtil.getParam(), vo);
        return PageUtil.getResult(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Dic dic) {
        Dic repDic = baseMapper.selectById(dic.getId());
        if(dic == null) {
            throw new DataNotFoundException();
        }
        baseMapper.updateById(dic);
        if(!dic.getCode().equals(repDic.getCode())) {
            dicItemMapper.update(null, Wrappers.<DicItem>lambdaUpdate().eq(DicItem::getCode, repDic.getCode())
                    .set(DicItem::getCode, dic.getCode()));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Dic dic = baseMapper.selectById(id);
        if(dic == null) {
            throw new DataNotFoundException();
        }
        baseMapper.deleteById(id);
        dicItemMapper.delete(Wrappers.<DicItem>lambdaQuery().eq(DicItem::getCode, dic.getCode()));
    }
}
